#include <iostream>
#include <cstring>

using namespace std;

int d[10000];
int z, i, m, l;
int ntest = 0;

int main()
{
	while (cin >> z >> i >> m >> l)
	{
		if (m == 0) break;

		memset(d, 0xFF, sizeof(d));
		d[l] = 0;
		int count = 0;

		cout << "Case " << (++ntest) << ": ";
		while (true)
		{
			l = (z*l+i)%m;
			count++;
			if (d[l] != -1)
			{
				cout << count - d[l] << endl;
				break;
			}
			else d[l] = count;
		}
	}
	return 0;
}
